In [1]:
import os
Create System independent path

In [2]:
os.path.join('usr', 'bin', 'spam')


Out[2]:
'usr/bin/spam'

In [3]:
#The Current Working Directory
os.getcwd()


Out[3]:
'/home/sudhanshu/GitHub/Fun-Tool/Learn'

In [14]:
#Move to desktop
os.chdir(os.path.join('/','home','sudhanshu','Desktop'))
os.getcwd()


Out[14]:
'/home/sudhanshu/Desktop'

In [5]:
#ABasolute path
os.path.abspath('.')
#return absolute path of current working directory becouse '.' specify current working directory


Out[5]:
'/home/sudhanshu/GitHub/Fun-Tool/Learn'

In [7]:
os.path.abspath('../') #return absolute address of relative directory '../'


Out[7]:
'/home/sudhanshu/GitHub/Fun-Tool'

In [12]:
#check given address is absolute or not
print os.path.isabs('/home/sudhanshu/GitHub/Fun-Tool')
print os.path.isabs('../')
print os.path.isabs(os.path.abspath('../'))
print os.path.isabs(os.getcwd())


True
False
True
True

Calculate Relative path with respect to some location


In [15]:
print os.path.relpath('/home/sudhanshu/', '/home/sudhanshu/GitHub/Fun-Tool')
print os.path.relpath('/home/sudhanshu/GitHub/Fun-Tool','/home/sudhanshu/')


../..
GitHub/Fun-Tool

Calculation of basename & directory name


In [16]:
path = 'home/sudhanshu/GitHub/Fun-Tool/readme.md'
print os.path.basename(path)
print os.path.dirname(path)


readme.md
home/sudhanshu/GitHub/Fun-Tool

Using Split function


In [17]:
print os.path.split(path)


('home/sudhanshu/GitHub/Fun-Tool', 'readme.md')

In [19]:
#Split into each sublocation
path.split(os.path.sep)


Out[19]:
['home', 'sudhanshu', 'GitHub', 'Fun-Tool', 'readme.md']

Finding File Sizes and Folder Contents


In [35]:
#calculate size of a file
path='/home/sudhanshu/Downloads/dropbox_2015.10.28_amd64.deb'
print os.path.getsize(path)/float(1024),'KB'


93.005859375 Bytes

In [2]:
#calculate size of a folder
#first find all file inside that folder
fileList=os.listdir('/home/sudhanshu/Downloads')
print fileList
print 'Sum of size of each file gives, size of folder'

folderSize=0
for filename in fileList:
    folderSize+=os.path.getsize(os.path.join('/home/sudhanshu/Downloads/',filename))
print 'folder Size of /home/sudhanshu/Downloads is:',float(folderSize)/(1024*1024),'MB'


['PSO_meander-line.ppt', 'bic_pso.ppt', 'NIT Rourkela LOI Not Received List.xls', 'Convolution_schematic.gif', '.~lock.train.csv#', 'pandoc-1.15.2.1.zip', 'OT-2015-11-16.zip', 'weka-3-6-13.zip', 'wxWidgets-3.0.2.tar.bz2.part', 'kaggle-titanic-master.zip', 'PDlabReport 112cs0174 112cs0148.rar', 'dropbox_2015.10.28_amd64.deb', '11165137_784821094965513_524151771649833897_o.jpg', '12265909_604395499699834_708160517436415650_o.jpg', '5131-15894-1-PB.pdf', 'PDlabReport 112cs0174 112cs0148', '42556139.jpg', 'blue_wave_2478.zip.part', 'incompletereg171115.xlsx', 'plot_digits_classification_001.png', 'pandoc-1.15.2.zip', 'Improving the performance of particle swarm optimization using ad.pdf', 'pedersen08simplifying.pdf', '1254376720000_Implementation of Nature Inspired optmization Algorithm.pdf', 'install_flash_player_11_linux.x86_64.tar.gz', 'Formal-title-page-template.docx', '905840_362917503867819_2182411091696402596_o.jpg', 'Cyberoam_SSL_CA.pem', 'xampp-linux-x64-5.6.14-4-installer.run', 'mongoDB with Python_1.html', '12238476_1078621588814541_919913457300341135_o.jpg', 'final_year_Project-2015-11-17.zip']
Sum of size of each file gives, size of folder
folder Size of /home/sudhanshu/Downloads is: 341.223345757 MB

Checking Path Validity

Calling os.path.exists(path) will return True if the file or folder referred to in the argument exists and will return False if it does not exist.
Calling os.path.isfile(path) will return True if the path argument exists and is a file and will return False otherwise.
Calling os.path.isdir(path) will return True if the path argument exists and is a folder and will return False otherwise.


In [9]:
print os.path.exists('/home/sudhanshu')
print os.path.exists('/home/sudhanshu/Downloads/dropbox_2015.10.28_amd64.deb')


True
True

In [11]:
print os.path.isdir('/home/sudhanshu/Downloads/dropbox_2015.10.28_amd64.deb') # return false becouse its a file not directory
print os.path.isdir('/home/sudhanshu/Downloads')


False
True

In [12]:
print os.path.isfile('/home/sudhanshu/Downloads/dropbox_2015.10.28_amd64.deb')
print os.path.isfile('/home/sudhanshu/Downloads')


True
False

Read Text file


In [ ]:
f = open('filename.extention','r')
#read entire file at a time
fileContent=f.read()
#read each line
lst=f.readlines()
f.close()

Saving Variables with the shelve Module

The shelve module will let you add Save and Open features to your program. For example, if you ran a program and entered some configuration settings, you could save those settings to a shelf file and then have the program load them the next time it is run.


In [2]:
import shelve

In [13]:
#writing data
shelfFile = shelve.open('mydata')
cats = ['Zophie', 'kitty', 'Simon']
cost=[34435,1332,3452]

shelfFile['cats']=cats #Stores cat var in file
shelfFile['cost']=cost
shelfFile.close() #close file

In [14]:
#reading data
shelfFile = shelve.open('mydata')
print type(shelfFile)
print shelfFile['cats'] #read variables
print shelfFile['cost']


<type 'instance'>
['Zophie', 'kitty', 'Simon']
[34435, 1332, 3452]

Ckeck keys stored in shelfFile


In [17]:
#return keys
print list(shelfFile.keys())
#return values
print list(shelfFile.values())


['cats', 'cost']
[['Zophie', 'kitty', 'Simon'], [34435, 1332, 3452]]

Saving Variables with the pprint.pformat() Function


In [19]:
import pprint
#deals with json formate

In [20]:
cats = [{'name': 'Zophie', 'desc': 'chubby'}, {'name': 'Pooka', 'desc': 'fluffy'}]
pprint.pformat(cats)


Out[20]:
"[{'desc': 'chubby', 'name': 'Zophie'}, {'desc': 'fluffy', 'name': 'Pooka'}]"

In [21]:
#Writing data
f = open('myCats.py', 'w')
f.write('cats = ' + pprint.pformat(cats) + '\n')
#it simply create a python file
f.close()

In [22]:
# Now import Python file & use
import myCats
myCats.cats


Out[22]:
[{'desc': 'chubby', 'name': 'Zophie'}, {'desc': 'fluffy', 'name': 'Pooka'}]

In [ ]: